import logging
import os
import shutil
from http.client import responses
from tempfile import NamedTemporaryFile

import emoji
from fastapi import UploadFile
from langchain_core.messages import HumanMessage, AIMessage

from models.ASR_model import wav_to_text
from models.chat_tts import get_chat_tts_model
from entity.database.mysql import History, Session, SessionAndHistory
from entity.schema.chat_schema import HistoryOutput
from entity.schema.model_schema import ModelOutput
from exception.custom_exception import CustomErrorThrowException
from models.GPT_SoVits_model import gpt_sovits_tts_model
from models.edge_model import text_to_speech_edge_tts
from models.pyttsx3_model import text_to_speech_pyttsx3
from models.qwen3_model import Qwen3Model
import re
import base64

from utils.Process_text import preprocess_text

'''
通过文本与大模型对话逻辑处理
'''
async def chat(question: str, session_id: int):
    histories = await get_history_by_session_id(session_id)

    # 调用大模型，并将历史记录传入大模型
    model = Qwen3Model(chat_history=histories)
    response = await model.chat(question)
    response = re.sub(r"(<think>.*?</think>\s+)", "", response, flags=re.S)
    # 确保 response 为有效字符串
    if not isinstance(response, str):
        print(f"Invalid response format: {response}")
        response = "Invalid response"

    question_record = await History.create(content=HumanMessage(content=question).model_dump_json(include={
        "type",
        "content"
    }))
    response_record = await History.create(content=AIMessage(content=response).model_dump_json(include={
        "type",
        "content"
    }))
    await SessionAndHistory.create(session_id=session_id, history_id=question_record.id)
    await SessionAndHistory.create(session_id=session_id, history_id=response_record.id)




    # answer_list = [string.strip() for string in answer.split("\n") if string.strip()]
    #
    # voice_data_url_list = []
    # for answer in answer_list:
    #     clean_answer = await preprocess_text(answer)
    #     logging.info(f"clean_answer:{clean_answer}")
    #     voice_bytes = await get_chat_tts_model(clean_answer)
    #     voice_data_url = f"data:audio/wav;base64,{base64.b64encode(voice_bytes).decode('utf-8')}"
    #     voice_data_url_list.append(voice_data_url)

    #调用pyttsx3模型
    # answer = emoji.replace_emoji(answer, replace="")
    clean_answer = await preprocess_text(response)
    # voice =await text_to_speech_pyttsx3(clean_answer)
    voice=await text_to_speech_edge_tts(clean_answer)
    voice = base64.b64encode(voice).decode('utf-8')

    return ModelOutput(answer=response, voice=voice)


'''
创建一个新的会话
'''
async def set_session():
    response=await Session.create()
    return response.id


'''
通过session_id获取历史记录
'''
async def get_history_by_session_id(session_id: int):
    histories = []
    history_session = await Session.get_or_none(id=session_id)
    if history_session is None:
        raise CustomErrorThrowException(status_code=501, detail="session_id不存在")
    else:
        # 将获取的历史记录存入数组中
        histories_contact_list = await SessionAndHistory.filter(session_id=session_id).order_by('created_time')
        for history_contact in histories_contact_list:
            history = await History.get(id=history_contact.history_id)
            history_content = history.content  # 获取历史记录内容

            # 确保历史记录格式正确
            if not isinstance(history_content,dict) or 'type' not in history_content or 'content' not in history_content:
                print(f"Invalid chat history format: {history_content}")


            histories.append(history_content)  # 添加格式正确的历史记录
    return histories

'''
获取所有的消息记录
'''
async def get_history_all():
    histories=await History.all()
    response=[]
    for history in histories:
        response.append(HistoryOutput.from_orm(history))
    return response

async def chat_with_audio(session_id: int, file: UploadFile):
    with NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
        shutil.copyfileobj(file.file,tmp)
        temp_path = tmp.name

    text =await wav_to_text(temp_path)
    os.remove(temp_path)
    response = await chat(text, session_id)
    return response




